const Koa = require('koa');
const { WebSocketServer } = require('ws')
const fs = require('fs')
const process = require('process');

const static = require('./static')

const { workJoin, domain, port } = require('./config');

require('./tools/listen')

const app = new Koa()

app.use(async (ctx, next) => {
    if(ctx.URL.href.slice(0, -1) === ctx.URL.origin)
    console.log(ctx.ip);
    await next()
})

/**静态托管 */
app.use(static)

var options = {
    https: true,
    oninit(hs, server) {
        const ws = new WebSocketServer({
            server
        })

        let wss = new Set

        ws.on('connection', (ws) => {
            wss.add(ws)
            ws.on('close', () => {
                wss.delete(ws)
            })
        })
        /**刷新页面 */
        function refresh() {
            wss.forEach(ws => {
                ws.send(JSON.stringify({
                    modifyFile: 'any'
                }))
            })
        }
        /**进程间通信 */
        process.on('message', (m) => {
            if (m === 'refresh') {
                refresh()
            }
        })
    },
    start() {
        console.log('run server to ' + domain);
    },
    key: fs.readFileSync(workJoin("./app/ssl/flycran.xyz.key")),
    cert: fs.readFileSync(workJoin("./app/ssl/flycran.xyz.crt"))
};

app.listen(port, options)